<!--

 * @Description: 关联交易项目
-->

<template>
  <page-view>
    <template #tabBar>
      <header-title class="head-title">
        <template #title>
          <el-space class="detail-info" :size="24">
            <span><span class="label">名称：</span>{{ transactionData.configName }}</span>
            <span><span class="label">年度：</span>{{ transactionData.belongYear }}</span>
            <span><span class="label">状态：</span>{{ transactionData.enableStatus ? '启用' : '停用' }}</span>
            <span><span class="label">创建人：</span>{{ transactionData.createUser }}</span>
            <span><span class="label">创建时间：</span>{{ $datetimeFormatter(null, null, transactionData.createTime) }}</span>
          </el-space>
        </template>
        <template #btn>
          <el-button v-if="isEdit" type="primary" @click="onTransactionEdit">编 辑</el-button>
          <el-button @click="onBack">返 回</el-button>
        </template>
      </header-title>
    </template>
    <template #form>
      <SearchForm :data-form="formInLine" @on-search="onSearch" @onReset="onSearch">
        <el-form-item prop="orgName">
          <el-input v-model="formInLine.orgName" placeholder="请输入关联单位名称" clearable/>
        </el-form-item>
        <el-form-item prop="projectCode">
          <el-input v-model="formInLine.projectCode" placeholder="请输入关联项目编码" clearable/>
        </el-form-item>
        <el-form-item prop="bizDescribe">
          <el-input v-model="formInLine.bizDescribe" placeholder="请输入预计业务描述" clearable/>
        </el-form-item>
        <el-form-item prop="bizDepCodes">
          <FsSelect v-model="formInLine.bizDepCodes" multiple collapse-tags  clearable :request-method="busunessTypeList" placeholder="请选择主体"/>
        </el-form-item>
        <el-form-item prop="belongGroup">
          <el-input v-model="formInLine.belongGroup" placeholder="请输入所属集团" clearable/>
        </el-form-item>
        <el-form-item prop="relatedTransTypeName">
          <el-input v-model="formInLine.relatedTransTypeName" placeholder="请输入关联交易类型" clearable/>
        </el-form-item>
      </SearchForm>
    </template>
    <template #option v-if="isEdit">
      <div class="btn-box">
        <el-button type="primary" @click="onAdd">新增</el-button>
        <el-button type="primary" :disabled="selectList.length == 0" @click="onBatchEnable">启用</el-button>
        <el-button type="primary" :disabled="selectList.length == 0" @click="onBatchDisable">停用</el-button>
        <el-button type="primary" :disabled="selectList.length == 0" @click="onBatchDel">删除</el-button>
      </div>
    </template>
    <template #table="tableScope">
      <PubilcTable :table-data="tableData" show-select show-index is-slot :page-data="pageData" :tableHeight="tableScope.tableHeight"
        @on-action="onAction" @on-selectChange="onSelectChange">
        <el-table-column v-if="isEdit" type="selection" width="40" align="center"/>
        <el-table-column label="序号" type="index" width="60"/>
        <el-table-column label="主体" prop="bizDepNames" min-width="100px"/>
        <el-table-column label="所属集团" prop="belongGroup" min-width="140px"/>
        <el-table-column label="关联单位" prop="orgNames" min-width="220px" show-overflow-tooltip/>
        <el-table-column label="关联项目编号" prop="projectCode" min-width="140px"/>
        <el-table-column label="预计业务描述" prop="bizDescribe" min-width="220px" show-overflow-tooltip/>
        <el-table-column label="归口部门" prop="belongDepartmentName" min-width="160px" />
        <el-table-column label="公告数(元)" prop="noticeAmount" min-width="140px" :formatter="$moneyFormatter" />
        <el-table-column label="累计发生额(元)" prop="usedAmount" min-width="140px" :formatter="$moneyFormatter" />
        <el-table-column label="可使用金额(元)" prop="remainingAmount" min-width="140px" :formatter="$moneyFormatter"/>
        <el-table-column label="执行进度" prop="progress" min-width="120px">
          <template #default="{ row, $index }">
            {{ (row.progress * 100).toFixed(2) + '%' }}
          </template>
        </el-table-column>
        <el-table-column label="关联交易类型" prop="relatedTransTypeName" min-width="160"/>
        <el-table-column label="收/付" prop="transType" width="100">
          <template #default="{ row, $index }">
            {{ $statusText(payReceiveOptions, row.transType) }}
          </template>
        </el-table-column>
        <el-table-column v-if="isEdit" label="操作" prop="id" width="160px" fixed="right">
          <template #default="{ row, $index }">
            <el-button link @click="onEdit(row, $index)">编辑</el-button>
            <el-button v-if="!row.enableStatus" link @click="onEnable(row, $index)">启用</el-button>
            <el-button v-else link @click="onDisable(row, $index)">停用</el-button>
            <el-button link :disabled="row.enableStatus" @click="onDel(row, $index)">删除</el-button>
          </template>
        </el-table-column>
      </PubilcTable>
    </template>
    <TransactionForm v-model="visible" :data="currentData" @success="requestDetail"/>
    <TransactionProjectForm v-model="projectVisible" :data="currentProject" @success="onSearch"/>
  </page-view>
</template>
<script setup name="RelatedTransaction">
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import * as relatedApi from '@/api/Reimbursement/related-transaction.js'
import TransactionForm from './components/transaction-form.vue'
import FsSearchSelect from '@/components/FsSearchSelect/index.vue'
import FsSelect from '@/components/FsSelect/index.vue'
import { remoteSupplierList, busunessTypeList } from '@/api/old-fssc'
import TransactionProjectForm from './components/transaction-project-form.vue'
import { payReceiveOptions } from './config'

const router = useRouter();
const route = router.currentRoute
const routeParams = route.value.params
const isEdit = routeParams.type === 'edit'

const formInLine = ref({})

const pageData = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const selectList = ref([])
const tableData = ref([])
const onSearch = () => {
  const params = {relatedTransConfigId: routeParams.id, ...formInLine.value, ...pageData }
  relatedApi.transactionProjectPage(params).then((res) => {
    tableData.value = res.list || []
    pageData.total = res.total || 0
  })
}

const onAction = ([item, row]) => {
  const obj = {
    'pageNum': onSearch,
    'pageSize': onSearch
  }
  if (typeof item === 'string') {
    pageData[item] = row
    if (item === 'pageSize') pageData.pageNum = 1
    obj[item]()
  } else {
    obj[item.alias](row)
  }
}

const onSelectChange = (list) => {
  selectList.value = list
}

const requestDel  = async (ids) => {
  await relatedApi.transactionProjectBatchDel(ids)
  onSearch()
}

const requestStatusChange = async (ids, enableStatus) => {
  await relatedApi.transactionProjectBatchStatus({ids, enableStatus})
  onSearch()
}

const onBack = () => {
  router.back(-1)
}

// 当前关联交易
const transactionData = ref({})
const requestDetail = () => {
  relatedApi.relatedTransactionDetail(routeParams.id).then((data) => {
    transactionData.value = data
  })
}
const visible = ref(false)
const currentData = ref()
const onTransactionEdit = () => {
  currentData.value = {
    type: 'edit',
    data: transactionData.value
  }
  visible.value = true
}


const projectVisible = ref(false)
const currentProject = ref({})
const onAdd = () => {
  currentProject.value = {
    relatedTransConfigId: routeParams.id
  }
  projectVisible.value = true
}

const onBatchEnable = async ({done}) => {
  try {
    if (selectList.value.some(item => item.enableStatus)) {
      ElMessage.warning('启用数据无法启用')
      done()
      return
    }
    await ElMessageBox.confirm(`您确定启用${selectList.value.length}条数据吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    requestStatusChange(selectList.value.map(item => item.id), true)
  } catch (e) {
    console.log(e)
  }
  done()
}

const onBatchDisable = async ({done}) => {
  try {
    if (selectList.value.some(item => !item.enableStatus)) {
      ElMessage.warning('停用数据无法停用')
      done()
      return
    }
    await ElMessageBox.confirm(`您确定停用${selectList.value.length}条数据吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    requestStatusChange(selectList.value.map(item => item.id), false)
  } catch (e) {
    console.log(e)
  }
  done()
}

const onBatchDel = async ({done}) => {
  try {
    if (selectList.value.some(item => item.enableStatus)) {
      ElMessage.warning('启用数据无法删除')
      done()
      return
    }
    await ElMessageBox.confirm(`您确定删除${selectList.value.length}条数据吗？删除后将不可恢复。`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    requestDel(selectList.value.map(item => item.id))
  } catch (e) {
    console.log(e)
  }
  done()
}

const onEdit = (row, index) => {
  currentProject.value = row
  projectVisible.value = true
}

const onEnable = (row, index) => {
  ElMessageBox.confirm(`您确定要进行启用操作吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    requestStatusChange([row.id], true)
  })
}
const onDisable = (row, index) => {
  ElMessageBox.confirm(`您确定要进行停用操作吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    requestStatusChange([row.id], false)
  })
}
const onDel = async (row, index) => {
  await ElMessageBox.confirm(`您确定要进行删除操作吗？删除后将不可恢复。`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  requestDel([row.id])
}

requestDetail()
onSearch()
</script>

<style lang="scss" scoped>
.head-title {
  :deep(.btn-box) {
    flex-shrink: 0;
  }
}

.detail-info {
  margin: 0 0 0 -20px;
  font-size: 14px;
  font-weight: normal;

  .label {
    color: #666;
  }
}
</style>
